/*
 * modAutorizacion.java
 *
 * Created on 22 de agosto de 2008, 04:37 PM
 */

package administrador;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import calendario.*;
import java.sql.Date;
import java.util.Calendar;
import javax.swing.JOptionPane;


/**
 *
 * @author  daniel1
 */
public class modAutorizacion extends javax.swing.JFrame {
 Usuario user;
 
 Conexion conexion;
 JTable tabla;
 JScrollPane js;
 Parametros pVent;
 
 Presentacion preVent;
 String bandera="";
 
 //Calendario
  calendario.JCalendar jCalendar = null;
  
 
    /** Creates new form modAutorizacion */
    public modAutorizacion(Conexion cEnt,Usuario user,Parametros pEnt) {
        pVent=pEnt;
        conexion=cEnt;
        this.user=user;
        
        
        jCalendar = new calendario.JCalendar(this, "Calendario",true);
        
        
        initComponents();
        setBounds(200,100,650,350);
        refrescar();
        setVisible(true);
        bandera="Parametros";
    }
    
    public modAutorizacion(Conexion cEnt,Usuario user,Presentacion pEnt) {
        preVent=pEnt;
        conexion=cEnt;
        this.user=user;
        
        
        jCalendar = new calendario.JCalendar(this, "Calendario",true);
        
        
        initComponents();
        setBounds(200,100,650,350);
        refrescar();
        setVisible(true);
        bandera="Presentacion";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        txt_num = new javax.swing.JTextField();
        txt_ff = new javax.swing.JTextField();
        txt_fi = new javax.swing.JTextField();
        txt_cod = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(administrador.AdministradorApp.class).getContext().getResourceMap(modAutorizacion.class);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setFont(resourceMap.getFont("jPanel1.font")); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setLayout(null);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(100, 200, 145, 23);

        txt_num.setText(resourceMap.getString("txt_num.text")); // NOI18N
        txt_num.setName("txt_num"); // NOI18N
        txt_num.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_numKeyTyped(evt);
            }
        });
        jPanel1.add(txt_num);
        txt_num.setBounds(100, 160, 150, 20);

        txt_ff.setText(resourceMap.getString("txt_ff.text")); // NOI18N
        txt_ff.setName("txt_ff"); // NOI18N
        jPanel1.add(txt_ff);
        txt_ff.setBounds(100, 130, 110, 20);

        txt_fi.setText(resourceMap.getString("txt_fi.text")); // NOI18N
        txt_fi.setName("txt_fi"); // NOI18N
        jPanel1.add(txt_fi);
        txt_fi.setBounds(100, 100, 110, 20);

        txt_cod.setEditable(false);
        txt_cod.setText(resourceMap.getString("txt_cod.text")); // NOI18N
        txt_cod.setName("txt_cod"); // NOI18N
        jPanel1.add(txt_cod);
        txt_cod.setBounds(100, 70, 150, 20);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jPanel1.add(jLabel1);
        jLabel1.setBounds(40, 60, 37, 30);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N
        jPanel1.add(jLabel2);
        jLabel2.setBounds(20, 90, 61, 30);

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N
        jPanel1.add(jLabel3);
        jLabel3.setBounds(30, 130, 50, 20);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N
        jPanel1.add(jLabel4);
        jLabel4.setBounds(40, 150, 41, 30);

        jLabel5.setFont(resourceMap.getFont("jLabel5.font")); // NOI18N
        jLabel5.setForeground(resourceMap.getColor("jLabel5.foreground")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N
        jPanel1.add(jLabel5);
        jLabel5.setBounds(10, 30, 184, 17);

        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(210, 100, 40, 20);

        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton3);
        jButton3.setBounds(210, 130, 40, 20);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    this.sacarFecha(1);
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
    this.sacarFecha(2);
}//GEN-LAST:event_jButton3ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    //Valido que el numero de autorizacion no se repita:
    String numero=this.txt_num.getText();
    int digitos=numero.length();
   //System.out.println("Los digitos "+digitos);
    if(digitos!=10){
    JOptionPane.showMessageDialog(this,"El numero de Autorizacion debe tener 10 digitos","Informacion",JOptionPane.INFORMATION_MESSAGE);
    }else{
    ResultSet resp=conexion.consultarBase("SELECT * FROM autorizacion where numero="+numero+";");
    int fila=0;
    try {
        resp.next();
        fila=resp.getInt(1);
    } catch (SQLException ex) {
        Logger.getLogger(modAutorizacion.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    if(fila>0){
    JOptionPane.showMessageDialog(this,"Este numero de Autorizacion ya ha sido Ingresada Anteriormente.","Informacion",JOptionPane.INFORMATION_MESSAGE);
    }else{
    
    int codigo=Integer.valueOf(txt_cod.getText());
    String fechaI=txt_fi.getText();
    String fechaF=txt_ff.getText();
    
    
    
    //Valido la Fechas a Ingresar:
    int ultimoCodigo=codigo-1;
    resp=conexion.consultarBase("select * from autorizacion where cod_auto="+ultimoCodigo);
    String ultimaFechaF="2000-01-01";
        try {
            resp.beforeFirst();
            resp.next();
            ultimaFechaF=resp.getDate("fecha_fin").toString();
        } catch (Exception ex) {
            Logger.getLogger(modAutorizacion.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    if (!txt_num.getText().toString().equals("") && (txt_num.getText().toString().length() == 10)) {
       //System.out.println("Compara = "+fechaI+" > "+ultimaFechaF+" res="+fechaI.compareTo(ultimaFechaF));
        if (fechaI.compareTo(ultimaFechaF) > 0) {
           //System.out.println("Compara = "+fechaF+" > "+fechaI+" res="+fechaF.compareTo(fechaI));
            if (fechaF.compareTo(fechaI) > 0) {

                conexion.consultarBase("START TRANSACTION;");
                boolean exito = conexion.insertarDatosR("insert into autorizacion values(" + codigo + ",'" + fechaI + "','" + fechaF + "'," + numero + ")");
                boolean exito2 = conexion.insertarDatosR("update parametros set autorizacion="+numero+" ,fech_cad='"+ fechaF +"';");
                if (exito && exito2) {
                    conexion.consultarBase("COMMIT;");
                    refrescar();
                } else {
                    conexion.consultarBase("ROLLBACK;");
                    JOptionPane.showMessageDialog(this, "Existen problemas en la insercion de Datos", "Informacion", JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Las fechas Fin de Autorizacion debe ser mayor a la Fecha Inicio de autorizacion", "Informacion", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Las fechas de Inicio de Autorizacion debe ser mayor a la Fecha de la ultima autorizacion", "Informacion", JOptionPane.INFORMATION_MESSAGE);
        }

    }else{
            JOptionPane.showMessageDialog(this, "El numero de autorizacion debera tener 10 digitos", "Informacion", JOptionPane.INFORMATION_MESSAGE);
    }
    }}
}//GEN-LAST:event_jButton1ActionPerformed

private void txt_numKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_numKeyTyped
// TODO add your handling code here:
    char c = evt.getKeyChar();
    if (!(Character.isDigit(c) || (c == java.awt.event.KeyEvent.VK_BACK_SPACE) || (c == java.awt.event.KeyEvent.VK_DELETE))) {
          getToolkit().beep();
          evt.consume();
          
    }
    String textoV=txt_num.getText();
    if(!(textoV.length()<10)){
     evt.consume();
    }
        
    
}//GEN-LAST:event_txt_numKeyTyped
public void refrescar(){
        String consulta="";
        consulta="SELECT * FROM autorizacion;";
        
        //cod_usuario as Codigo,nombre as Nombre,privilegios as Privilegios
        ResultSet respuesta=null;
        respuesta=conexion.consultarBase(consulta);
          
        //Obtengo Filas-Arreglo de Titulos de Columnas
        int filas=conexion.obtenerFilas(respuesta);
        String[] titulosCol=conexion.obtenerColumnas(respuesta);
        
        //Creo la tabla:
        
        CrearTabla(filas,titulosCol);
        llenaTabla(respuesta,titulosCol.length,filas);
        
        //Lleno Datos Iniciales:
        String fecha=new java.sql.Date(System.currentTimeMillis()).toString();
        txt_fi.setText(fecha);
        
        int codigo=0;
        try {
            java.sql.ResultSet resp = conexion.consultarBase("select MAX(cod_auto) from autorizacion;");
            resp.beforeFirst();
            resp.next();
            codigo=resp.getInt(1)+1;
        } catch (SQLException ex) {
            
        }
       this.txt_cod.setText(String.valueOf(codigo));
       //Limpio datos ingresador:
       txt_ff.setText("");
       txt_num.setText("");
       
       if(bandera.equals("Parametros")){
           pVent.refrescar();
       }
       if(bandera.equals("Presentacion")){
           preVent.refrescar();
           
       }
       
    }
     public void llenaTabla(ResultSet r,int columnas,int filas){
        try{
            r.beforeFirst();
            
            int j=0;
            while(r.next()) {
                
                
                for(int i=0;i<columnas;i++) {
                    
                    Object toma=r.getObject(i+1);
                    //System.out.println("toma valor:"+toma+" * fila:"+j+" * column:"+i);
                    try{
                        tabla.setValueAt(toma,j,i);
                    }catch(java.lang.ArrayStoreException e){
                        tabla.setValueAt("null",j,i);
                    }
                }
                
            j++;    
            }
        }catch(SQLException sqle){
           //System.out.println("Error al mostrar los datos");
            System.err.println(sqle);
        }
        
    }
    
public void CrearTabla(int filas,String[] titulos){
        
        int columnas=titulos.length;
        String[][] tabla0=new String[filas][columnas];
       
        tabla= new JTable(tabla0,titulos);
        
        //Aqui le especifico para que la tabla acepte valores doubles e int:
        //--------------------------------------------------------------------
        final boolean[] canEdit = new boolean [columnas];
        for(int p=0;p<columnas;p++){
        canEdit[p]=false;
        }
        tabla.setModel(new javax.swing.table.DefaultTableModel(
            tabla0,titulos  
        ) {
           // boolean[] canEdit = new boolean [] { false, false, false, false};

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        //---------------------------------------------------------------------
         //Le doy el evento del LCick del Mouse:
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        //remuevo el JScroll para que no se monte cuando cree el nuevo:
        //*************************************************************
        try{
        jPanel1.remove(js);
        }catch(java.lang.NullPointerException e){}
        //*************************************************************
        
        //Pongo en la tabla:
            js = new JScrollPane(tabla);
                        
            js.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(198, 196, 196)));
            js.setBounds(300,25, 300, 250);
            js.setVisible(true);
            jPanel1.add(js);
            js.updateUI();
    }
 
public void sacarFecha(int opcion) {

        Calendar cDate = jCalendar.getCalendar();
        if (cDate == null) {
            cDate = Calendar.getInstance();
        }

        jCalendar.setCalendar(cDate);
        jCalendar.setVisible(true);

        if (jCalendar.isOkPressed()) {
            java.sql.Date fecha = new java.sql.Date(jCalendar.getDate().getTime());
            if (opcion == 1) {
                txt_fi.setText(fecha.toString());
            } else if (opcion == 2) {
                txt_ff.setText(fecha.toString());
            }
            jCalendar.setVisible(false);
        }

    }
 private void tablaMouseClicked(java.awt.event.MouseEvent evt) {
    // Evento del click del mouse sobre la tabla:
        
 }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txt_cod;
    private javax.swing.JTextField txt_ff;
    private javax.swing.JTextField txt_fi;
    private javax.swing.JTextField txt_num;
    // End of variables declaration//GEN-END:variables

}
